<template>
  <back-dialog-base
    :title="title"
    :visible="visibleDialog"
    width="20rem"
    @onCommit="handleSubmit"
    @onCloesa="closeDlog"
    @emits="show"
  >
    <template #content>
      <div class="content-warp">
        <div class="left-form">
          <el-form
            v-show="choseType === true"
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="120px"
          >
            <el-row>
              <el-col :span="140">
                <el-form-item label="巡检类型：" prop="patrolType">
                  <el-select
                    v-model="form.patrolType"
                    placeholder="请选择"
                    size="large"
                  >
                    <el-option
                      v-for="item in allTypeData"
                      :key="item"
                      :label="item"
                      :value="item"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="140">
                <el-form-item label="所属管廊：" prop="pipeId">
                  <el-select
                    v-model="form.pipeId"
                    placeholder="请选择"
                    size="large"
                  >
                    <el-option
                      v-for="item in allPipeData"
                      :key="item.id"
                      :label="item.pipeName"
                      :value="item.pipeCode"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="140">
                <el-form-item label="所属仓室：" prop="storehouseId">
                  <el-select
                    v-model="form.storehouseId"
                    placeholder="请选择"
                    size="large"
                  >
                    <el-option
                      v-for="item in allhouserData"
                      :key="item.id"
                      :label="item.name"
                      :value="item.code"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="140">
                <el-form-item label="防火分区：" prop="subregionId">
                  <el-select
                    v-model="form.subregionId"
                    placeholder="请选择"
                    size="large"
                  >
                    <el-option
                      v-for="item in allSubregionData"
                      :key="item.id"
                      :label="item.name"
                      :value="item.code"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="巡检点位置：" prop="list">
              <el-scrollbar height="65px">
                <el-checkbox-group v-model="form.list">
                  <el-checkbox
                    v-for="(item, index) in loctin"
                    :key="index"
                    :label="item.id"
                    >{{ item.location }}</el-checkbox
                  >
                </el-checkbox-group>
              </el-scrollbar>
            </el-form-item>
            <el-row>
              <el-form-item label="巡检内容：" prop="patrolContent">
                <el-input
                  v-model="form.patrolContent"
                  @click="choseList"
                  placeholder="请输入…"
                ></el-input>
              </el-form-item>
            </el-row>
            <el-row>
              <el-col :span="140">
                <el-form-item label="开始时间：" prop="patrolStartTime">
                  <el-date-picker
                    v-model="form.patrolStartTime"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    type="datetime"
                    placeholder="--请选择--"
                    @change="dateChange"
                    @calendar-change="calendarChange"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="140">
                <el-form-item label="结束时间：" prop="patrolEndTime">
                  <el-date-picker
                    v-model="form.patrolEndTime"
                    format="YYYY-MM-DD hh:mm:ss"
                    value-format="YYYY-MM-DD hh:mm:ss"
                    type="datetime"
                    placeholder="--请选择--"
                    @change="dateChange"
                    @calendar-change="calendarChange"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="140">
                <el-form-item label="巡检人员：" prop="patrolPerson">
                  <el-input
                    v-model="form.patrolPerson"
                    placeholder="请输入…"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="140">
                <el-form-item label="巡检班长：" prop="patrolMonitor">
                  <el-input
                    v-model="form.patrolMonitor"
                    placeholder="请输入…"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <!-- 巡检内容输入弹框 -->
          <div v-show="choseType === false">
            <el-row :span="24">
              <el-col :span="7">
                <div class="type">巡检类型</div>
                <el-tree
                  :data="oneArr"
                  :highlight-current="true"
                  :props="defaultProps"
                  @node-click="handleNodeClick"
                ></el-tree>
              </el-col>
              <el-col :span="1"> </el-col>
              <el-col :span="7">
                <div class="block">
                  <el-scrollbar height="300px">
                    <el-checkbox-group
                      v-model="checkListNone"
                      @change="noneSelect"
                    >
                      <el-checkbox
                        v-for="(item, index) in leftCheckbox"
                        :key="index"
                        class="check"
                        :value="item"
                        :label="item"
                        >{{ item }}</el-checkbox
                      >
                    </el-checkbox-group>
                  </el-scrollbar>
                </div>
              </el-col>
              <el-col :span="1"> </el-col>
              <el-col :span="7">
                <div class="block">
                  <div>已选名单</div>
                  <div class="dele">
                    <el-checkbox
                      v-model="checkAll"
                      :indeterminate="isIndeterminate"
                      @change="handleCheckAllChange"
                    >
                      全选
                    </el-checkbox>
                    <div class="delete" @click="deleteRight">删除</div>
                  </div>
                  <el-scrollbar
                    height="calc(300px - 60px)"
                    style="padding-left: 20px"
                  >
                    <el-checkbox-group
                      v-model="checkListHas"
                      @change="handleCheckedCitiesChange"
                    >
                      <el-checkbox
                        v-for="(item, index) in rightCheckbox"
                        :key="index"
                        class="check"
                        :value="item"
                        :label="item"
                        @click="handleCheckedCitiesChangea(item, index)"
                        >{{ item }}</el-checkbox
                      >
                    </el-checkbox-group>
                  </el-scrollbar>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>
      </div>
    </template>
  </back-dialog-base>
</template>

<script setup>
import {
  reactive,
  defineProps,
  ref,
  defineEmits,
  watch,
  defineExpose,
  nextTick
} from 'vue'
import BackDialogBase from '@/components/BackDialogBase'
import { message } from '@/utils/message'
import { ElMessage } from 'element-plus'
import {
  allType,
  allhouser,
  allPipe,
  allSubregion,
  allPosition,
  allPoint,
  allPointType,
  scheduleSave
} from '@/api/patrolScheme'
import store from '@/store'
const props = defineProps({
  title: {
    type: String,
    default: ''
  },
  visibleDialog: {
    type: Boolean,
    default: false
  },
  rowData: {
    type: Object,
    default: () => {}
  }
})
const emits = defineEmits(['onReload'])
const formRef = ref(null)
const choseType = ref(true)
const checkListNone = ref([])
const checkListHas = ref([]) //已选名单
const checkAll = ref(false) //全选
const isIndeterminate = ref(true) //全选
//右侧已选列表
const rightCheckbox = ref([])
//左侧列表
const leftCheckbox = ref([])
const allTypeData = ref([])
const allhouserData = ref([])
const allPipeData = ref([])
const allSubregionData = ref([])
const allPosti = ref([])
const loctin = ref([])
let form = ref({
  patrolType: '', //类型
  pipeId: '', //管廊
  storehouseId: '', //仓库
  subregionId: '', //区域
  list: [], //巡检点
  patrolContent: '', //巡检内容
  patrolStartTime: '', //巡检开始时间
  patrolEndTime: '', //巡检结束时间
  patrolPerson: '', //巡检人员
  patrolMonitor: '', //巡检班长
  patrolMonth: new Date().getFullYear() + '-' + (new Date().getMonth() + 1) //巡检月份
})
const rules = reactive({
  patrolType: [
    {
      required: true,
      message: '巡检类型不能为空',
      trigger: 'change'
    }
  ],
  pipeId: [
    {
      required: true,
      message: '所属管廊不能为空',
      trigger: 'change'
    }
  ],
  storehouseId: [
    {
      required: true,
      message: '所属仓室不能为空',
      trigger: 'change'
    }
  ],
  subregionId: [
    {
      required: true,
      message: '防火分区不能为空',
      trigger: 'change'
    }
  ],
  list: [
    {
      required: true,
      message: '巡检点位置不能为空',
      trigger: 'blur'
    }
  ],
  patrolContent: [
    {
      required: true,
      message: '巡检内容不能为空',
      trigger: 'change'
    }
  ],
  patrolStartTime: [
    {
      required: true,
      message: '开始时间不能为空',
      trigger: 'blur'
    }
  ],
  patrolEndTime: [
    {
      required: true,
      message: '结束时间不能为空',
      trigger: 'blur'
    }
  ],
  patrolPerson: [
    {
      required: true,
      message: '巡检人员不能为空',
      trigger: 'blur'
    }
  ],
  patrolMonitor: [
    {
      required: true,
      message: '巡检班长不能为空',
      trigger: 'blur'
    }
  ]
})
//所有巡检类型
const allTypeList = async () => {
  let res = await allType()
  let resPipe = await allPipe()
  let resSubregion = await allSubregion()
  let reshouser = await allhouser()
  let allposti = await allPosition()
  let allponitType = await allPointType()
  leftCheckbox.value = allponitType
  // console.log('allponitType', allponitType)
  allTypeData.value = res
  allhouserData.value = reshouser
  allPipeData.value = resPipe
  allSubregionData.value = resSubregion
  loctin.value = allposti
}
allTypeList()
const qwe = (res) => {
  console.log('res', res)
}
const choseList = () => {
  // console.log('form.value.list', form.value.list)
  if (form.value.list.length !== 0) {
    choseType.value = false
    emits('changeTitle', choseType.value)
    getallPoint(form.value.list)
  } else {
    message({ type: 'error', message: '请先选择巡检点位置!' })
  }
  // console.log('prop', props.title)
}
const oneArr = ref([])
//根据巡检点位置查询所有巡检点
const getallPoint = async (data) => {
  let a = data
  let res = await allPoint(a)
  oneArr.value = res
}
//关闭弹窗的方法
const updateFun = () => {
  formRef.value.resetFields()
  emits('onReload')
}
const handleSubmit = () => {
  if (choseType.value !== false) {
    formRef.value.validate((valid) => {
      if (valid) {
        save(Object.assign(props.rowData, form.value))
        console.log('验证通过')
        updateFun()
      } else {
        console.log('验证错误')
        return false
      }
    })
  } else {
    form.value.patrolContent = rightCheckbox.value.toString()
    choseType.value = true
    emits('changeTitle', choseType.value)
  }
}
const closeDlog = () => {
  if (choseType.value === false) {
    choseType.value = true
    form.value.patrolContent = rightCheckbox.value.toString()
    emits('changeTitle', choseType.value)
  } else {
    formRef.value.resetFields()
    emits('onCloes')
  }
}
const cleara = () => {
  nextTick(() => {
    formRef.value.clearValidate()
  })
}
//巡检计划表保存
var save = async (form) => {
  const res = await scheduleSave(form)
  message({ type: 'success', message: '新增成功!' })
  //     clearForm()
  emits('onReload')
}
watch(
  () => props.visibleDialog,
  () => {
    // console.log(22222222)
  }
)

const clearForm = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
  form.value = {}
}
const handleNodeClick = (data) => {}

const defaultProps = {
  children: 'children',
  label: 'label'
}
const handleCheckAllChange = (val) => {
  const all = rightCheckbox.value.map((item) => {
    return item.id
  })
  checkListHas.value = val ? all : []
  isIndeterminate.value = false
  // console.log(checkListHas.value)
}
const arra = ref([])
const handleCheckedCitiesChangea = (item, index) => {}
const handleCheckedCitiesChange = (value) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === rightCheckbox.value.length
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < rightCheckbox.value.length
}
const noneSelect = (val) => {
  val.map((item) => {
    if (rightCheckbox.value.indexOf(item) === -1) {
      rightCheckbox.value.push(item)
    }
    // console.log(rightCheckbox.value.indexOf(item))
  })
}
const deleteRight = () => {
  const res = getArrDifference(rightCheckbox.value, checkListHas.value)
  const r = getArrDifference(checkListNone.value, checkListHas.value)
  rightCheckbox.value = res
  checkListNone.value = r
  checkListHas.value = []
}
const getArrDifference = (arr1, arr2) => {
  return arr1.concat(arr2).filter(function (v, i, arr) {
    return arr.indexOf(v) === arr.lastIndexOf(v)
  })
}
defineExpose({ allTypeList, cleara })
</script>
<style lang="scss" scoped>
.content-warp {
  width: 100%;
  height: 100%;
  display: flex;
  .left-form {
    flex: 4;
  }
  .right-form {
    flex: 6;
    height: 780px;
    overflow: auto;
    padding-left: 60px;
    &::-webkit-scrollbar-track-piece {
      background: #d3dce6;
    }

    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-thumb {
      background: #d6d6d680;
      border-radius: 20px;
    }
    .item-form {
      width: 100%;
      display: flex;
      margin-bottom: 30px;
      .title {
        width: 80px;
        font-size: 14px;
        font-family: Microsoft YaHei;
        line-height: 19px;
        color: #333333;
        display: flex;
        .line-tag {
          width: 4px;
          height: 14px;
          background: #ff9502;
          border-radius: 4px;
          margin-right: 5px;
        }
      }
      .form-content {
        width: calc(100% - 120px);
        display: flex;
        flex-direction: column;
        .btns-row {
          width: 100%;
          height: 35px;
          display: flex;
          position: relative;
          margin-bottom: 6px;
          .tags {
            width: calc(100% - 45px);
            display: flex;
            column-gap: 4px;
            overflow-x: auto;
            &::-webkit-scrollbar-track-piece {
              background: #d3dce6;
            }

            &::-webkit-scrollbar {
              width: 3px;
              height: 3px;
            }

            &::-webkit-scrollbar-thumb {
              background: #ff9502;
              border-radius: 20px;
            }
          }
          .add-btn {
            width: 40px;
            height: 32px;
            background: rgba(255, 255, 255, 0.39);
            border: 1px solid #ff9502;
            border-radius: 5px;
            font-size: 12px;
            font-family: Microsoft YaHei;
            font-weight: 400;
            line-height: 30px;
            color: #ff9502;
            text-align: center;
            position: absolute;
            right: 0;
            cursor: pointer;
            &:hover {
              background: rgba(255, 255, 255, 0.22);
            }
          }
        }
        .form-card {
          width: 100%;
          border: 1px solid #d3dbe5;
          border-radius: 4px;
          padding: 20px;
        }
      }
    }
  }
}
.type {
  height: 60px;
  text-align: center;
  line-height: 60px;
  background: #f2f2f2;
}
.block {
  width: 100%;
  //   height: 300px;
  border: 1px solid #797979;
  white-space: nowrap;
  overflow-y: auto;
  padding: 10px;
  border-radius: 5px;
}
.check {
  display: block !important;
}
.dele {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.delete {
  border-radius: 5px;
  border: 1px solid #f56c6c;
  color: #f56c6c;
  width: 70px;
  font-size: 16px;
  text-align: center;
  height: 30px;
  line-height: 30px;
}
.delete:hover {
  border: 1px solid #f56c6c;
  color: #fff;
  background: #f56c6c;
}
</style>
